package com.str;

public class ReverseWordsInaString0201_151 {
    public String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int len = chars.length;
        char[] ret = new char[len + 1];
        int subIdx = 0;
        for (int i = len-1, j = len-1; i >=0 && j>=0; i--) {
            //j 排除空格，找到元素
            if(chars[j] == ' '){
                j--;
                continue;
            }

            //j 找到要移动的 字符串首位
            while (j>=0 && chars[j] != ' '){
                j--;
            }
            for (int k = j+1; k <= i; k++) {
                ret[subIdx++] = chars[k];
            }
            ret[subIdx++] = ' ';
            i = j+1;
        }
        return new String(ret, 0, subIdx-1);
    }
}
